package com.example.demo03.web;

import com.example.demo03.pojo.User;
import com.example.demo03.service.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 2. 接收前端提交的请求参数
        String uName = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        // 3. 将请求参数封装到User实体类对象中
        User user = new User();
        user.setUsername(uName);
        user.setPassword(pwd);
        // 4. 创建业务层即service层的对象
        UserServiceImpl userService = new UserServiceImpl();
        // 5. 使用业务层对象调用业务层的登录方法将user对象传递到业务层
        User u = userService.login(user);
        // 6. 判断u是否等于null
        if (u==null){
            // 等于空说明没有查到用户，登录失败，响应给前端false
            response.getWriter().print(false);
        } else {
            // 设置用户session
            HttpSession session = request.getSession();
            session.setAttribute("u", u);
            System.out.println("用户登陆成功");
            // 不等空说明查到用户，登陆成功，响应true
            response.getWriter().print(true);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
